package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.RoleDao;
import com.itheima.entity.PageResult;
import com.itheima.pojo.Role;
import com.itheima.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;

    /**
     * 分页查询所有角色
     * @param currentPage
     * @param pageSize
     * @param queryString
     * @return
     */
    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        //1.设置分页参数
        PageHelper.startPage(currentPage,pageSize);
        //2.需要分页的语句
        Page<Role> rolePage = roleDao.selectByCondition(queryString);
        return new PageResult(rolePage.getTotal(),rolePage.getResult());
    }

    /**
     * 删除角色
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        //根据角色id查询角色与菜单关联表
        int count = roleDao.findMenuByRoleId(id);
        if (count > 0){
            throw new RuntimeException(MessageConstant.DELETE_ROLEANDMenu_FAIL);
        }
        //根据角色id查询角色与权限关联表
        int count2 = roleDao.findPerByRoleId(id);
        if (count2 > 0){
            throw new RuntimeException(MessageConstant.DELETE_ROLEANDPER_FAIL);
        }
        //根据角色id查询角色与用户关联表
        int count3 = roleDao.findUserByRoleId(id);
        if (count3 > 0){
            throw new RuntimeException(MessageConstant.DELETE_ROLEANDUSER_FAIL);
        }
        //都不存在关系是直接删除角色
        roleDao.delete(id);
    }

    /**
     * 查询所有角色供用户勾选
     * @return
     */
    @Override
    public List<Role> findAll() {
        return roleDao.findAll();
    }
}
